#ifndef Networking_Server_H
#define Networking_Server_H

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <pthread.h>
#include <vector>

#include "Networking_ServerClient.h"
#include "Networking_Exceptions.h"

namespace Networking
{

  void *HandleClient(void * cptr);

  class Server
  {
    int PortNumber;
    int SocketFileDiscriptor;
    struct sockaddr_in ServerAddress;
    
    void EmptyServerAddress()
    {
      memset(&ServerAddress, 0, sizeof(ServerAddress));
    }
    
    void BindToPort()
    {
      if (bind(SocketFileDiscriptor, (struct sockaddr *) &ServerAddress, sizeof(ServerAddress)) < 0)
      {
	printf("ERROR on binding");
      }
    }
    
    void AcceptClients()
    {
      struct sockaddr_in TempClientAddress;
      socklen_t TempClientAddressLength = sizeof(TempClientAddress);
      Client * cli = new Client( accept(SocketFileDiscriptor, (struct sockaddr *) &TempClientAddress, &TempClientAddressLength));
      cli->SetSocketAddress(TempClientAddress);
      pthread_create( &(cli->Thread), NULL, HandleClient, (void *)cli );
    }

  public:
    Server(int pn)
    {
      PortNumber = pn;
      SocketFileDiscriptor = socket(AF_INET, SOCK_STREAM, 0);
      if (SocketFileDiscriptor < 0)
      {
	printf("ERROR opening socket");
      }
      EmptyServerAddress();
      ServerAddress.sin_family = AF_INET;
      ServerAddress.sin_addr.s_addr = INADDR_ANY;
      ServerAddress.sin_port = htons(PortNumber);
    }
    
    ~Server()
    {

    }
    
    void Bind()
    {
      BindToPort();
    }
    
    void Listen()
    {
      while (1)
      {
	listen(SocketFileDiscriptor,5);
	AcceptClients();
      }
    }

    void Listen(int BackLogMax)
    {
      while(1)
      {
	listen(SocketFileDiscriptor, BackLogMax);
	AcceptClients();
      }
    }
  };

  void *HandleClient( void *Cfd )
  {
    Client * cp = reinterpret_cast<Client*>(Cfd);
    while (1)
    {
      if (!cp->Read())
	break;
    }
  }

}

#endif